package com.rh.security;

import com.rh.result.ResultVo;
import com.rh.utils.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 退出管理器
 * 实现SpringSecurity中的LogoutHandler接口,重写里面logout方法
 */
public class TokenLogoutHandler implements LogoutHandler {
    //注入Token管理器
    private TokenManager tokenManager;
    //注入Redis模板
    private RedisTemplate redisTemplate;

    //有参构造方法
    public TokenLogoutHandler(TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }
    /**
     * 退出的核心,重写LogoutHandler里面logout方法
     */
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //1.先从请求头获取token
        String token = request.getHeader("token");
        //2.判断token是否存在，并移除token并从redis中删除
        if (token != null) {
            //删除token信息
            tokenManager.removeToken(token);
            //清空当前用户缓存中的权限数据
            String userName = tokenManager.getUserFromToken(token);
            redisTemplate.delete(userName);
        }
        ResponseUtil.out(response, ResultVo.ok());
    }
}